<template>

  <div>

    <Card>

      <div class="p-relative" style="padding-top: 10px;">
        <div @click="refresh" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">
          <div class="flex-item search-btn" @click="sendCoupon">
            <Button type="info">发送优惠券</Button>
          </div>
          <div class="flex-item">
            <Input v-model="searchObj.keywords" placeholder="请输入姓名或手机号" style="width: 150px" />
          </div>
          <div class="flex-item">
           <Select v-model="searchObj.store_id" style="width:180px" placeholder='请选择会员类型' @on-change="changStore">
              <Option v-for="item in data.storeList" :value="item.id" :key="item.id">{{ item.name }}会员</Option>
            </Select>
          </div>
          <div class="flex-item search-btn" @click="search">
            <Button type="warning">搜索</Button>
          </div>
          <div class="flex-item search-btn" @click="reset">
            <Button>重置</Button>
          </div>

        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" @on-selection-change="changeUser" border :no-data-text="loadingText ? loadingText : '暂无数据'" border
        ref="tables" editable search-place="top">
        <template slot-scope="{ row, index }" slot="id">
          {{row.business_id>0?row.b_id:row.id}}
        </template>
        <template slot-scope="{ row, index }" slot="create_time">
          {{row.business_id>0?row.b_create_time:row.create_time}}
        </template>
        <template slot-scope="{ row, index }" slot="balance">
          {{row.business_id>0?row.b_balance:row.balance}}
        </template>
        <template slot-scope="{ row, index }" slot="mobile">
          {{row.business_id>0?row.tel:row.mobile}}
        </template>
        <template slot-scope="{ row, index }" slot="username">
          <span v-if="row.business_id>0">
              {{row.related_name}}
          </span >
           <span v-else>
              {{row.username?row.username:row.nickname}}
           </span>
        </template>
        <template slot-scope="{ row, index }" slot="business_id">
          {{row.business_id>0?row.store_name+'会员':'平台会员'}}
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='warning' @click="detail(row, index)" size='small'>查看</Button>
          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>

    </Card>

    <!-- 查看弹窗 -->
    <!-- @on-ok="ok" @on-cancel="cancel" -->
    <Modal v-model="detailModal" title="订单详情" width='60%'>
      <div class="detail-table">
        <div class="base-info">
          <Row class='row-main-title font16 table-head-bg padding10'>
            <Col span="24">会员信息</Col>
          </Row>
          <Row class='row-main-content'>
            <Col span="6" class='padding10'><span
              class="font-gray">姓名：</span>{{data.detail.username?data.detail.username:data.detail.nickname}}
                {{data.detail.business_id>0?'(门店会员)':'(平台会员)'}}
              </Col>
            <Col span="6" class='padding10'><span class="font-gray">手机号码：</span>{{data.detail.mobile}}</Col>
            <Col span="6" class='padding10'><span class="font-gray">会员等级：</span>{{data.detail.vip_name}}</Col>
              <Col span="6" class='padding10'><span class="font-gray">注册日期：</span>{{data.detail.create_time}}</Col>
          </Row>
          <Row class='row-main-content'>
            <Col span="6" class='padding10'><span class="font-gray">运动卡余额：</span>
            ￥{{data.detail.balance}}元
            </Col>
            <Col span="6" class='padding10'><span class="font-gray">累计购卡金额：</span>￥{{data.detail.wallet_amount}}元</Col>
            <Col span="6" class='padding10'><span class="font-gray">累计购卡赠送：</span>￥{{data.detail.give_amount}}元</Col>
             <Col span="6" class='padding10'><span class="font-gray">门店：</span>{{data.detail.store_name}}</Col>

          </Row>
          <Row class='row-main-content'>
              <Col span="6" class='padding10'><span class="font-gray">累计预约金额：</span>￥{{data.totalMakeAmount}}元</Col>
             <Col span="6" class='padding10'><span class="font-gray">累计课程金额：</span>￥{{data.totalCourseAmount}}元</Col>

          </Row>
        </div>

      </div>
      <div class="detail-table">
        <div class="base-info">
          <Row class='row-main-title font16 table-head-bg padding10'>
            <Col span="2">消费记录
            </Col>
            <Col span="22" style="text-align: right;">
              <Input v-model="searchObj1.keywords" placeholder="类目 如:羽毛球" style="width:110px;margin-right: 5px;" />
              <Select v-model="searchObj1.pay_type" style="width:120px;text-align: left;margin-right: 5px;" placeholder='请选择支付方式' @on-change="changPayType">
                <Option v-for="item in payType" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
              <Select v-model="searchObj1.related_type" style="width:120px; text-align: left;margin-right: 5px;" placeholder='请选择消费类型' @on-change="changeOrderType">
                <Option v-for="item in related_type" :value="item.value" :key="item.value">{{ item.name }}</Option>
              </Select>
              <Select v-model="searchObj1.order_estate" style="width:120px;text-align: left;margin-right: 5px;" placeholder='请选择订单状态' @on-change="changEstate">
                <Option v-for="item in orderEstate" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
              <DatePicker @on-change="changeCreateTime" type="daterange" placeholder="请选择下单时间" style="width: 180px">
              </DatePicker>
               <Button type="warning" @click="detailSearch">搜索</Button>
               <Button @click="detailReset">重置</Button>
            </Col>
          </Row>

          <Table :columns="table1Option" :data="data.orderList" border
            :no-data-text="loadingText ? loadingText : '暂无数据'" border ref="tables" editable search-place="top">
            <template slot-scope="{ row, index }" slot="content">
              <span v-if="row.related_type==1">{{row.card_name}}</span>
              <span v-else>{{row.store_name}} {{row.venue_name}}</span>
            </template>
            <template slot-scope="{ row, index }" slot="amount">
              {{row.related_type==1?'+ ':'- '}}{{row.amount}}
            </template>
            <template slot-scope="{ row, index }" slot="cancel_fee">
              <span v-if="row.order_estate==5 && row.cancel_fee>0">
               {{row.related_type==1?'+ ':'- '}}{{row.cancel_fee}}
              </span>

            </template>
            <template slot-scope="{ row, index }" slot="related_type">
              {{row.related_type==1?'运动卡购买':'场馆预约'}}
            </template>
          </Table>
          <Page class="foot-page" :current='page.current1' :total="page.total1" :page-size="page.pageSize1" show-total
            show-elevator @on-change="changepage1"></Page>

        </div>

      </div>
      <div slot="footer">
        <Button @click='detailModal=false'>关闭</Button>

      </div>
    </Modal>

    <!-- 发送优惠券弹窗 -->
    <Modal v-model="couponModal" title="发送优惠券" width='60%'>
      <div class="flex-box search-area">
        <div class="flex-item">
          <Input v-model="couponSearchObj.keywords" placeholder="请输入优惠券名称" style="width: 150px" />
        </div>
        <div class="flex-item search-btn" @click="couponSearch">
          <Button type="warning">搜索</Button>
        </div>
        <div class="flex-item search-btn" @click="couponReset">
          <Button>重置</Button>
        </div>

      </div>
      <Table :columns="table2Option" :data="data.couponList" @on-selection-change="changeCoupon" border :no-data-text="loadingText ? loadingText : '暂无数据'"
        border ref="tables" editable search-place="top">

        <template slot-scope="{ row, index }" slot="spend_money">
          {{row.spend_money>0?row.spend_money:'无门槛'}}
        </template>
        <template slot-scope="{ row, index }" slot="send_num">
          {{parseInt(row.send_num)-parseInt(row.receive_num)}}张
        </template>
          <template slot-scope="{ row, index }" slot="action">
            <div class="flex-box flex-center flex-margin">
              <Button type='warning' @click="sendTip(row, index)" size='small'>发送</Button>

            </div>
          </template>
      </Table>
      <Page class="foot-page" :current='page.current2' :total="page.total2" :page-size="page.pageSize2" show-total
        show-elevator @on-change="changepage2"></Page>
        
      <div slot="footer">
        <Button @click='couponModal=false'>关闭</Button>

      </div>
    </Modal>

    <!-- 发送优惠券提示弹窗 -->
    <Modal v-model="couponTipModal" title="提示" width="500">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定要向{{changeUserids.length}}位用户发送【{{couponItem.name}}】优惠券码？
      </p>
      <div slot="footer">
        <Button @click='couponTipModal=false'>取消</Button>
        <Button type="primary" @click='confirmSend'>确定</Button>
      </div>
    </Modal>
  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState
  } from 'vuex'
  import {
    permission
  } from '@/config/permission.js'
  import {
    formatDate
  } from '@/config/publicTool.js' // 日期转换,//调用的时候formatDate(),不需要this
  // 接口
  import {
    getList,
    getDetail,
    getCoupon,
    sendCoupon
  } from '@/api/users-group/user'
  import {
    tableOption
  } from '../../../data/users-group/user.js'
  import Tables from '_c/tables'
  import {
    getTableData
  } from '@/api/data'

  export default {
    name: 'tables_page',
    components: {
      Tables
    },
    created() {
      let _this = this

      this.$nextTick(function() {
        // 权限校验
        _this.role_detail = permission(this.roles, 'user/detail')
        _this.role_coupon = permission(this.roles, 'coupon/getList')

      })

      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({
        roles: state => state.user.roles
      }),

    },
    data() {
      return {
        // 权限标识
        role_add: false,
        role_edit: false,
        role_del: false,
        role_detail: false,
        role_coupon:false,
        detailModal: false,
        loadingText: '',
        tableOption: tableOption,
        table1Option: [{
            title: 'ID',
            key: 'id',
            width: '70'

          },
          {
            title: '内容',
            key: 'username',
            slot: 'content',
            width: '310'
          },
          {
            title: '消费类型',
            key: 'related_type',
            slot: 'related_type',
             align: 'center',
              width: '90',
          },
          {
            title: '支付方式',
            key: 'pay_type_name',
             width: '90',
              align: 'center',
          },
          {
            title: '订单状态',
            key: 'order_estate',
             width: '90',
              align: 'center',
            render: (h, params) => {
              let order_estate = params.row.order_estate;
              let order_text = '';
              if(params.row.related_type==1){
                  switch (order_estate) {
                    case 0:
                      order_text = '已取消'
                      break;
                    case 1:
                      order_text = '已充值'
                      break;
                    default:
                      '-'
                  }
              }else{
                switch (order_estate) {
                  case 1:
                    order_text = '未使用'
                    break;
                  case 2:
                    order_text = '使用中'
                    break;
                  case 3:
                    order_text = '已使用'
                    break;
                  case 4:
                    order_text = '取消中'
                    break;
                  case 5:
                    order_text = '已取消'
                    break;
                  default:
                    '-'
                }
              }


              return h('span', {
                style: {
                  color: '#ff6600'
                }
              }, order_text)
            }

          },
          {
            title: '金额(元)',
            key: 'amount',
            align: 'right',
            slot: 'amount',
            width: '100'
          },
          {
            title: '取消扣费(元)',
            key: 'cancel_fee',
             slot: 'cancel_fee',
            align: 'right',
            width: '110'
          },
          {
            title: '下单日期',
            key: 'create_time'
          },
        ],
        searchObj: {
          create_time: '',
          keywords: '',
          store_id:''

        },
        searchObj1: {
          related_type:'',
          pay_type:'',
          order_estate:'',
          keywords:'',
          create_time: '',

        },
        couponSearchObj:{
            keywords: '',
        },
        page: {
          current: 1,
          total: 0,
          pageSize: 10,
          current1: 1,
          total1: 0,
          pageSize1: 10,
          current2: 1,
          total2: 0,
          pageSize2: 10
        },
        data: {
          detail: [],
          orderList: [],
          list: [],
          couponList:[],
          totalMakeAmount:0,
          totalCourseAmount:0,
          storeList:[]
        },
        businessId:0,
        rowId: 0,
        b_id:0,
        couponModal: false,
        //优惠券列表
        table2Option:[
       
          {
            title: '优惠券名称',
            key: 'name',

          },
          {
            title: '类型',
            key: 'limit_type',
            render: (h, params) => {
              let txt = '';
              switch (params.row.limit_type) {
                case 0:
                  txt = '无限制'
                  break;
                case 1:
                  txt = '订场'
                  break;
                case 2:
                  txt = '课程'
                  break;
                case 3:
                  txt = '课程单品'
                  break;
                case 4:
                  txt = '购物'
                  break;
              }

              return h('span', txt)
            }

          },

          {
            title: '优惠金额',
            key: 'coupon_money',
            align:'right'
          },
          {
            title: '满额使用',
            key: 'spend_money',
            align:'right',
             slot: 'spend_money',
          },
          {
            title: '剩余数量',
            key: 'send_num',
            align:'right',
             slot: 'send_num',
          },

          {
            title: '有效期限',
            key: 'use_expire_at'
          },
          {
            title: '操作',
            slot: 'action',
            align: 'center',
             width: 80,
          }
        ],
        couponTipModal:false,
        couponItem:[], //优惠券数据
        changeCouponids:[],//勾选中的优惠券id
        changeUserids:[],//勾选选中的用户id
        related_type:[
          {
            name:'全部',
            value:''
          },
          {
            name:'运动卡',
            value:'1'
          },
          {
            name:'场馆预约',
            value:'2'
          },
          {
            name:'课程',
            value:'5'
          }
        ],
        payType: [{
            id: '',
            name: '全部'
          },
          {
            id: 1,
            name: '微信'
          },
          {
            id: 2,
            name: '余额'
          },
          {
            id: 3,
            name: '支付宝'
          },
          {
            id: 4,
            name: '现金'
          }
        ],
        orderEstate: [{
            id: '',
            name: '全部'
          },
          {
            id: 1,
            name: '未使用'
          },
          {
            id: 2,
            name: '使用中'
          },
          {
            id: 3,
            name: '已使用'
          },
          {
            id: 4,
            name: '取消中'
          },
          {
            id: 5,
            name: '已取消'
          }
        ],
      }
    },
    methods: {
      // 列表数据
      getList() {
        let _this = this
        let create_time = this.searchObj.create_time[0] ? (formatDate(this.searchObj.create_time[0], 3) + ' - ' +
          formatDate(this.searchObj.create_time[1], 3)) : ''

        let params = {
          page: this.page.current,
          keywords: _this.searchObj.keywords,
          create_time: create_time,
          store_id:_this.searchObj.store_id
        }

        getList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list
            _this.page.total = result.total
            _this.page.pageSize = result.size
            _this.data.storeList = result.storeList
          }
        }).catch(function(error) {
          // 异常

        })
      },
      changepage(e) {
        this.page.current = e;
        this.getList();

      },
      changepage1(e) {
        this.page.current1 = e;
        this.detail({
          "id": this.rowId,
          'b_id':this.b_id,
          'business_id':this.businessId
        });

      },
      changepage2(e) {
        this.page.current2 = e;
        this.sendCoupon()
      },
      // 查看
      detail(row) {
        if (!this.role_detail) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }

        if(!this.detailModal){
           this.searchObj1 = {
             pay_type: '',
             related_type:'',
             order_estate:'',
             keywords:'',
             create_time:''
           }
        }

        this.rowId = row.id,
        this.businessId = row.business_id
        this.b_id = row.b_id  //商家会员表id

        this.detailModal = true

        let params = {
          id: this.rowId,
          page: this.page.current1,
          related_type:this.searchObj1.related_type,
          pay_type: this.searchObj1.pay_type,
          order_estate:this.searchObj1.order_estate,
          keywords:this.searchObj1.keywords,
          create_time:this.searchObj1.create_time,
          b_id:this.b_id,
          business_id:this.businessId
        }

        let _this = this;
        _this.data.detail = []
        getDetail(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.detail = result.data
            _this.data.orderList = result.list
            _this.page.total1 = result.total
            _this.page.pageSize1 = result.size
            _this.data.totalCourseAmount = result.totalCourseAmount
            _this.data.totalMakeAmount = result.totalMakeAmount
          }
        }).catch(function(error) {
          // 异常

        })

        // this.formItem.detail = row;

      },

      // 刷新
      refresh() {
        this.searchObj = {
          create_time: [],
          keywords: ''
        } // 清空搜索框
        this.getList()
      },
      // 重置
      reset() {
        this.searchObj = {
          create_time: [],

          keywords: ''
        } // 清空搜索框
        this.getList()
      },

      // 查询
      search() {
        this.getList()
      },
      //优惠券发送
      sendCoupon() {
        let _this = this;

        if(this.changeUserids.length<=0){
          let config = {
            content: '请勾选要发送的用户',
            background: true
          }
          this.$Message.error(config)
          return ;
        }
        this.couponModal = true;
        let params = {
          page: this.page.current2,
          name: _this.couponSearchObj.keywords,
        }
        getCoupon(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.couponList = result.list
            _this.page.total2 = result.total
            _this.page.pageSize2 = result.size
          }
        }).catch(function(error) {
          // 异常

        })
      },
      couponSearch() {
         this.sendCoupon()
      },
      couponReset(){
        this.couponSearchObj = {
          keywords: ''
        }
        this.sendCoupon()
      },
      changeUser(e){
        this.changeUserids = [];
        e.forEach((item)=>{
            this.changeUserids.push(item.id);
        })

      },
      changeCoupon(e){
        // this.changeCouponids = [];
        // e.forEach((item)=>{
        //     this.changeCouponids.push(item.id);
        // })
        // console.log(222,this.changeCouponids)
      },
      sendTip(item){
        this.couponTipModal = true;
        this.couponItem = item;
      },
      //确认发送
      confirmSend(){
        this.couponTipModal = false;
        //计算可发送的优惠券数量
        let remain_num = parseInt(this.couponItem.send_num) - parseInt(this.couponItem.receive_num);
        if(this.changeUserids.length>remain_num){
           this.$Message.error('发送人数超过可发送的优惠券数量')
           return
        }
         let params = {
           user_ids: this.changeUserids,
           coupon_ids: this.couponItem.id,
         }
         sendCoupon(params).then(res => {
           if (res.data.status == 1) {
                this.$Message.success('发送成功')
                this.sendCoupon()
           }
         }).catch(function(error) {
           // 异常
            this.$Message.error('发送失败')
         })
      },
      changeOrderType(e){
        this.searchObj1.related_type = e
       this.page.current1=1
        this.detail({
          "id": this.rowId,
          'b_id':this.b_id,
          'business_id':this.businessId
        });
      },
      changPayType(e) {
        this.searchObj1.pay_type = e
        this.page.current1=1
         this.detail({
           "id": this.rowId,
           'b_id':this.b_id,
           'business_id':this.businessId
         });
      },
      changEstate(e) {
        this.searchObj1.order_estate = e
        this.page.current1=1
         this.detail({
           "id": this.rowId,
           'b_id':this.b_id,
           'business_id':this.businessId
         });
      },
      detailReset(){
        this.searchObj1 = {
          pay_type: '',
          related_type:'',
          order_estate:'',
          keywords:'',
          create_time:''
        }
       this.page.current1=1
        this.detail({
          "id": this.rowId,
          'b_id':this.b_id,
          'business_id':this.businessId
        });
      },
      detailSearch(){
        this.page.current1=1
         this.detail({
           "id": this.rowId,
           'b_id':this.b_id,
           'business_id':this.businessId
         });
      },
      changeCreateTime(e) {
        this.searchObj1.create_time = e
      },
      changStore(){
        this.getList()
      }
    }

  }
</script>

<style lang="scss">
  @import "./index";
</style>
